#include <cstring>
#include <string>
#include <iostream>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
using namespace std;

#define Mode 0666
#define NAMEED_PIPE_Path "fifo"

class Fifo
{
public:
    Fifo(const string &path = NAMEED_PIPE_Path) : _path(path)
    {
        umask(0);
        int n = mkfifo(_path.c_str(), Mode);
        if (n < 0)
        {
            cerr << "mkfifo error:" << errno << endl;
        }
    }
    ~Fifo()
    {
        int n = unlink(_path.c_str());
        if (n < 0)
        {
            cerr << "unlink error:" << errno << endl;
        }
    }

private:
    string _path;
};

class Sync
{
public:
    void Openread(const char *path)
    {
        int fd = open(path, O_RDONLY);
        if (fd < 0)
        {
            perror("open read");
            exit(1);
        }
        _rfd = fd;
    }
    void Openwrite(const char *path)
    {
        int fd = open(path, O_WRONLY);
        if (fd < 0)
        {
            perror("open write");
            exit(1);
        }
        _wfd = fd;
    }
    bool SendSig() // 向管道中写入内容，表明我已经写好了，你可以去（某地）读数据了
    {
        int sig = 0;
        int w = write(_wfd, &sig, sizeof(sig));
        if (w < 0)
        {
            perror("write");
            exit(1);
        }
        return true;
    }
    // 从管道中读取内容，表明我接到通知了，要去（某地）读数据了；
    // 读了数据之后就又空了，会等待你下一次 send signal
    bool GetSig()
    {
        int sig = 0;
        int r = read(_rfd, &sig, sizeof(sig));
        if (r < 0)
        {
            perror("read");
            exit(1);
        }
        return true;
    }

private:
    int _wfd = -1;
    int _rfd = -1;
};
